#include "CONFIG.h"
#include "battery.h"

#include "broadcaster.h"

#include <stdio.h>
#include <string.h>

static uint8_t Battery_TaskID;

#define VREF (1.05f)

uint16_t Battery_ProcessEvent (uint8_t task_id, uint16_t events);

void Battery_Init (void) {
    Battery_TaskID = TMOS_ProcessEventRegister (Battery_ProcessEvent);

    tmos_set_event (Battery_TaskID, BATTERY_COLLECT_EVT);
}

uint16_t Battery_ProcessEvent (uint8_t task_id, uint16_t events) {

    if (events & SYS_EVENT_MSG) {
        uint8_t *pMsg;

        if ((pMsg = tmos_msg_receive (Battery_TaskID)) != NULL) {

            // Release the TMOS message
            tmos_msg_deallocate (pMsg);
        }

        // return unprocessed events
        return (events ^ SYS_EVENT_MSG);
    }

    if (events & BATTERY_COLLECT_EVT) {
        // Start the Collect battery
        uint16_t adcBuff = 0;
        uint8_t *scanRspDataPtr;
        char fmtBuf[5] = {0};
        float battVal = 0.f;

        ADC_InterBATSampInit();
        adcBuff = ADC_ExcutSingleConver();
        PRINT ("BAT = %X \n", adcBuff);
        battVal = ((float)adcBuff / 512 - 3) * VREF;

        scanRspDataPtr = Broadcaster_GetScanRspData();
        snprintf (fmtBuf, sizeof (fmtBuf), "%4.2f", battVal);
        memcpy (scanRspDataPtr + 25, fmtBuf, sizeof (fmtBuf) - 1);

        Broadcaster_UpdateAdvertisingData();

        tmos_start_task (Battery_TaskID, BATTERY_COLLECT_EVT, BATTERY_COLLECT_PERIOD);
        return (events ^ BATTERY_COLLECT_EVT);
    }

    // Discard unknown events
    return 0;
}